package com.fengwk.zuul.filter;

import java.io.File;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Pattern;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Value;
//import org.springframework.stereotype.Component;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;

import com.fengwk.support.util.ArrayUtils;
import com.fengwk.support.util.IoUtils;
import com.fengwk.support.util.LoggerUtils;
import com.fengwk.support.util.LoggerUtils.Logger;

//不启用
//@Component
public class ResourceFilter extends ZuulFilter {

	private static final Logger LOG = LoggerUtils.getLogger(ResourceFilter.class);
	
	private static final Pattern PATTERN_FILE = Pattern.compile("^/\\d{4}-\\d{2}-\\d{2}");
	
	@Value("${spring.resources.static-locations}")
	private String staticLocations;
	
	private Set<String> locations;
	
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return Integer.MIN_VALUE;
    }

    @Override
    public boolean shouldFilter() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        String uri = request.getRequestURI().toString().toLowerCase();
        
        boolean isResource = false;
        isResource = PATTERN_FILE.matcher(uri).find()
        		|| uri.contains(".html") 
        		|| uri.contains(".js")
        		|| uri.contains(".css")
        		|| uri.contains(".jpg")
        		|| uri.contains(".png")
        		|| uri.contains(".svg")
        		|| uri.contains(".ico")
        		|| uri.contains(".pdf")
        		|| uri.contains(".doc")
        		|| uri.contains(".docx")
        		|| uri.contains(".xls")
        		|| uri.contains(".xlsx")
        		|| uri.contains(".md")
        		|| uri.contains(".txt");
        
        // 请求URL内不包含login或join则需要经过该过滤器，即执行run()
        return isResource;
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        ServletOutputStream sos = null;
		try {
			sos = ctx.getResponse().getOutputStream();
			File file = getRealFile(request.getRequestURI());
			if (file != null) {
				// 禁止转发
				ctx.setSendZuulResponse(false);
				// 写入输出流
				sos.write(IoUtils.readBytes(file));
			}
		} catch (IOException e) {
		    LOG.error(e);
		} finally {
			IoUtils.close(sos);
		}
        return null;
    }
    
    private File getRealFile(String uri) {
    	String[] locationStrs = staticLocations.split(",");
    	if (locations == null) {
    		locations = new HashSet<>();
    		if (ArrayUtils.isNotBlank(locationStrs)) {
    			for (String locationStr: locationStrs) {
    				locations.add(locationStr.replace("file:", "").trim());
    			}
    		}
    	}
    	for (String location: locations) {
			File file = new File(location + uri);
			if (file.exists()) {
				return file;
			}
		}
		return null;
    }

}
